﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


namespace Script.Net.Scripts
{
	public class HttpContextScriptRepository : IScriptRepository
	{
		public HttpContextScriptRepository() { }



		private void AddItemToContext(IScriptItem item)
		{
			var ctx = GetContext();
			var container = (ScriptContainer)ctx.Items[typeof(HttpContextScriptRepository)];

			if (container.HasKey(item.Alias))
				throw new InvalidOperationException("A script with the same alias already exists: " + item.Alias);

			container.Add(item.Alias, item);

			ctx.Items[typeof(HttpContextScriptRepository)] = container;
		}

		public void CreateScript(ScriptFile file)
		{
			AddItemToContext(file);
		}

		public void CreateScript(ScriptContent content)
		{
			AddItemToContext(content);
		}

		private HttpContextBase GetContext()
		{
			var ctx = new HttpContextWrapper(HttpContext.Current);
			if (!ctx.Items.Contains(typeof(HttpContextScriptRepository)))
			{
				ctx.Items.Add(typeof(HttpContextScriptRepository), new ScriptContainer());
			}

			return ctx;
		}

		public IEnumerable<IScriptItem> GetScripts()
		{
			var ctx = new HttpContextWrapper(HttpContext.Current);
			return ((ScriptContainer)ctx.Items[typeof(HttpContextScriptRepository)]).GetAll();
		}
	}
}
